<template>
  <a-spin :spinning="loading">
    <JFormContainer :disabled="disabled || addDisabled ">
      <template #detail>
        <a-form v-bind="formItemLayout">
          <a-row>
            <a-col :span="12"  v-auth="'packaging:purchase'">
              <a-form-item v-bind="validateInfos.factoryId" label="工厂">
                <j-search-select placeholder="请选择工厂" v-model:value="formData.factoryId" dict="p_factory_manage,name,code" allow-clear />
              </a-form-item>
            </a-col>
            <a-col :span="12" >
              <!--							<a-form-item label="产品" v-bind="validateInfos.goodsNo" v-auth="'packaging:purchase'">-->
              <!--								<j-search-select placeholder="请输入产品编号搜索产品" v-model:value="formData.goodsNo" dict="goods_info,goods_name,goods_no"  allow-clear />-->
              <!--              </a-form-item>-->
              <a-form-item label="产品" v-bind="validateInfos.goodsNo">
                <j-search-select placeholder="请输入产品编号搜索产品" v-model:value="formData.goodsNo" :dictOptions="dictOptions"  allow-clear />
                <j-input :disabled="true" v-model:value="formData.goodsNo" ></j-input>
              </a-form-item>

            </a-col>
            <a-col :span="24">
              <a-form-item label="入库单入库时人工核对" v-bind="validateInfos.checking">
                <a-switch v-model:checked="formData.checking" checked-children="开" un-checked-children="关" />
                <!--								<j-search-select v-model:value="formData.specNo" :dict="specCodeDict"  allow-clear />-->
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </template>
    </JFormContainer>

    <!-- 子表单区域 -->
    <a-tabs v-model:activeKey="activeKey" animated>
      <a-tab-pane tab="产品绑定的包材" key="packagingProductRelation" :forceRender="true">
        <JVxeTable
          :keep-source="true"
          resizable
          ref="packagingProductRelationTableRef"
          :loading="packagingProductRelationTable.loading"
          :columns="packagingProductRelationTable.columns"
          :dataSource="packagingProductRelationTable.dataSource"
          :height="340"
          :disabled="disabled"
          :rowNumber="true"
          :rowSelection="true"
          :toolbar="true"
          @valueChange="handleValueChange"
        />
      </a-tab-pane>
    </a-tabs>
  </a-spin>
</template>

<script lang="ts">
import {defineComponent, ref, reactive, computed, toRaw, onMounted, watch, watchEffect} from 'vue';
import { useValidateAntFormAndTable } from '/@/hooks/system/useJvxeMethods';
import { queryPackagingProductRelationListByMainId, queryDataById } from '/@/views/packaging/relation/PackagingProduct.api'
import { JVxeTable } from '/@/components/jeecg/JVxeTable';
import {packagingProductRelationColumns} from '/@/views/packaging/relation/PackagingProduct.data';
import JSearchSelect from '/@/components/Form/src/jeecg/components/JSearchSelect.vue';
import JFormContainer from '/@/components/Form/src/container/JFormContainer.vue';
import { Form } from 'ant-design-vue';
import {JVxeLinkageConfig} from "@/components/jeecg/JVxeTable/src/types";
import {initDictOptions} from "@/utils/dict";
import { defHttp } from '/@/utils/http/axios';
const useForm = Form.useForm;
import { useUserStore } from '/@/store/modules/user';
import JInput from "@/components/Form/src/jeecg/components/JInput.vue";
import {manualVerification} from "@/views/packaging/verification/PurchaseOrderVerification.api";
const userStore = useUserStore();

export default defineComponent({
  name: "PackagingVerificationForm",
  components:{
    JInput,
    JSearchSelect,
    JVxeTable,
    JFormContainer,
  },
  props:{
    formDisabled:{
      type: Boolean,
      default: false
    },
    formData: { type: Object, default: ()=>{} },
    formBpm: { type: Boolean, default: true }
  },
  emits:['success'],
  setup(props, {emit}) {

    const loading = ref(false);
    const packagingProductRelationTableRef = ref();
    // 向每个列配置项添加 disabled 属性
    const updatedColumns = packagingProductRelationColumns.map(column => ({
      ...column,  // 保留原有的列配置
      disabled: true,  // 增加 disabled 属性
    }));
    const packagingProductRelationTable = reactive<Record<string, any>>({
      loading: false,
      columns: updatedColumns,
      dataSource: []
    });
    packagingProductRelationTable.dataSource
    const activeKey = ref('packagingProductRelation');
    const formData = reactive<Record<string, any>>({
      id: '',
      goodsNo: '',
      factoryId:'',
      checking:false,
      // specNo: '',
    });

    //表单验证
    const validatorRules = reactive({
      factoryId:[{required: true, message: '请选择工厂名称!'}],
      goodsNo: [{ required: true, message: '请输入产品编号!'},],
    });
    const {resetFields, validate, validateInfos} = useForm(formData, validatorRules, {immediate: false});
    const dbData = {};
    const formItemLayout = {
      labelCol: {xs: {span: 24}, sm: {span: 5}},
      wrapperCol: {xs: {span: 24}, sm: {span: 16}},
    };




    const  dictOptions = ref ([]);
    const  dictPackOptions = ref([]);

    const fetchDictOptions = async (factoryId) => { // 添加 async
      loading.value = true; // 开始加载
      try {
        // 使用 await 等待异步操作完成
        let url = '/packaging/factoryProduct/dict'
        if (factoryId) {
          url = '/packaging/factoryProduct/dict?factoryId='+factoryId
        }
        const res = await defHttp.get({ url: url });
        loading.value = false; // 加载结束

        if (res && res.length > 0) {
          dictOptions.value = res.map((item) => ({
            text: item.goodsName,
            value: item.goodsNo,
          }));
        } else {
          dictOptions.value = [];
        }
      } catch (e) {
        console.error('Error fetching factoryProduct dict:', e); // 添加错误日志
      }

      try {
        // 使用 await 等待异步操作完成
        let url = '/packaging/packagingDetails/dict'
        if (factoryId) {
          url = '/packaging/packagingDetails/dict?factoryId='+factoryId
        }
        const res = await defHttp.get({ url: url });
        loading.value = false; // 加载结束

        if (res && res.length > 0) {
          dictPackOptions.value = res.map((item) => ({
            text: item.name,
            value: item.id,
          }));
          packagingProductRelationTable.columns[0].options = dictPackOptions.value;
        } else {
          dictPackOptions.value = [];
          packagingProductRelationTable.columns[0].options = dictPackOptions.value;
        }
      } catch (e) {
        console.error('Error fetching packagingDetails dict:', e); // 添加错误日志
      }
    };

    watch(() => formData.factoryId, async (factoryId) => {
      await fetchDictOptions(factoryId)

      // console.log(packagingProductRelationTable.columns)
      // console.log(packagingProductRelationTable.dataSource)
    });

    // watch(() => formData.goodsNo, async (goodsNo) => {
    //   const packagingProductRelationDataList = await queryPackagingProductRelationListByMainId(goodsNo);
    //   packagingProductRelationTable.dataSource = [...packagingProductRelationDataList];
    //
    //   // console.log(packagingProductRelationTable.columns)
    //   // console.log(packagingProductRelationTable.dataSource)
    // });

    // 监听 dataSource 中的包装产品的 packagingId 变化，并设置 unit 值
    // watch(() => packagingProductRelationTable.columns, (newDataSource) => {
    //   console.log(newDataSource)
    //   newDataSource.forEach((row) => {
    //     if (row.packagingId === '1') {
    //       row.unit = 'pcs'; // 这里设置 unit 为 '个'
    //     } else {
    //       row.unit = '个'; // 或者设置为其他默认值
    //     }
    //   });
    // }, { immediate: true });
    const addDisabled = ref(false)
    // 表单禁用
    const disabled = computed(()=>{
      if(props.formBpm === true){
        if(props.formData.disabled === false){
          return false;
        }else{
          return true;
        }
      }
      return props.formDisabled;
    });

    async function add() {
      if(userStore.getUserInfo.factoryId) {
        validatorRules.factoryId[0].required = false
      }

      await fetchDictOptions(null);
      addDisabled.value = false
      resetFields();
      packagingProductRelationTable.dataSource = [];
    }

    function handleValueChange(event) {
      console.log('handleValueChange.event: ', event);
      console.log('handleValueChange.event: ', event.row);
      if (event.cellType = "select-search") {
        if (!isNaN(event.row.packagingId)) {
          const dictData = initDictOptions('p_packaging_details,unit,unit,'+ encodeURIComponent(`id = '${event.row.packagingId}'`))
          dictData.then(res=>{
            console.log(res[0])
            if (res[0]) {
              event.row.unit = res[0].text
            }else {
              event.row.unit = ''
            }
          })
        } else {
          // 不是数字
        }

      }


    }


    async function edit(row) {
      addDisabled.value = true
      //主表数据
      await fetchDictOptions(row.factoryId)
      // await queryMainData(row.id);
      //子表数据
      const tmpData = {};
      tmpData["id"] = row.id
      tmpData['goodsNo'] = row.goodsNo
      tmpData['factoryId'] = row.factoryId
      // tmpData['specNo'] = row.specNo
      Object.assign(formData,tmpData);
      const packagingProductRelationDataList = await queryPackagingProductRelationListByMainId(row['goodsNo']);
      packagingProductRelationTable.dataSource = [...packagingProductRelationDataList];
    }

    async function queryMainData(id) {
      const row = await queryDataById(id);
      const tmpData = {};
      Object.keys(formData).forEach((key) => {
        if(row.hasOwnProperty(key)){
          tmpData[key] = row[key]
        }

      })
      //赋值
      Object.assign(formData,tmpData);

    }

    const {getSubFormAndTableData, transformData} = useValidateAntFormAndTable(activeKey, {
      'packagingProductRelation': packagingProductRelationTableRef,
    });

    async function getFormData() {
      await validate();
      return transformData(toRaw(formData))
    }

    async function submitForm() {
      const mainData = await getFormData();
      const subData = await getSubFormAndTableData();
      const values = Object.assign({}, dbData, mainData, subData);
      console.log('表单提交数据', values)
      const isUpdate = values.id ? true : false
      await manualVerification(values);
      //关闭弹窗
      emit('success');
    }


    function setFieldsValue(values) {
      if(values){
        Object.keys(values).map(k=>{
          formData[k] = values[k];
        });
      }
    }

    /**
     * 值改变事件触发-树控件回调
     * @param key
     * @param value
     */
    function handleFormChange(key, value) {
      formData[key] = value;
    }

    // // 在组件挂载时加载数据
    // onMounted(() => {
    //   fetchDictOptions();
    // });



    return {
      handleValueChange,
      packagingProductRelationTableRef,
      packagingProductRelationTable,
      validatorRules,
      validateInfos,
      activeKey,
      dictOptions,
      dictPackOptions,
      loading,
      formData,
      setFieldsValue,
      handleFormChange,
      formItemLayout,
      disabled,
      addDisabled,
      getFormData,
      submitForm,
      add,
      edit,
      fetchDictOptions
    }
  }
});
</script>
<style lang="less" scoped></style>
